import { routerRedux } from 'dva/router';
import { fetchAssetDetail, addAssetEntity } from '../services/api';

export default {
  namespace: 'assetEntity',
  state: {
    step: {},
    submitting: false,
  },
  effects: {
    *fetchDetail({ payload }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(fetchAssetDetail, payload);

      yield put({
        type: 'loadAssetDetail',
        payload: response,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    // migrate action
    *submitAssetEntity({ payload }, { call, put }) {
      yield put({
        type: 'changeStepFormSubmitting',
        payload: true,
      });
      yield call(addAssetEntity, payload);
      yield put({
        type: 'saveStepFormData',
        payload,
      });
      yield put({
        type: 'changeStepFormSubmitting',
        payload: false,
      });
      yield put(routerRedux.push('/asset/add/result'));
    },
  },

  reducers: {
    saveStepFormData(state, { payload }) {
      return {
        ...state,
        step: {
          ...state.step,
          ...payload,
        },
      };
    },
    changeStepFormSubmitting(state, { payload }) {
      return {
        ...state,
        submitting: payload,
      };
    },
    changeLoading(state, { payload }) {
      return {
        ...state,
        loading: payload,
      };
    },
    loadAssetDetail(state, { payload }) {
      return {
        ...state,
        assetDetail: payload,
      };
    },
  },
};

